package com.emaxcard.agent.modules.controller;

import com.emax.channel.common.enums.PayChannelCodeEnum;
import com.emax.common.DubboApps;
import com.emax.trans.rpcapi.business.settle.agent.TransBigAgentApi;
import com.emax.trans.rpcapi.business.settle.agent.dto.*;
import com.emax.zhenghe.common.api.vo.MyIPage;
import com.emax.zhenghe.common.api.vo.Result;
import com.emax.zhenghe.common.api.vo.ResultX;
import com.emax.zhenghe.common.aspect.annotation.AutoLog;
import com.emaxcard.agent.modules.bigagent.settle.dto.BigAgentTransferDownDto;
import com.emaxcard.agent.modules.bigagent.settle.dto.BigAgentTransferDto;
import com.emaxcard.agent.modules.bigagent.settle.service.BigAgentTransferService;
import com.emaxcard.agent.modules.bigagent.settle.vo.BigAgentTransferVo;
import com.sby.common.export.AsyncExportContext;
import com.sby.common.export.AsyncExportHandler;
import com.sby.common.export.AsyncExportManager;
import com.sby.common.export.AsyncExportState;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 大渠道商 结算转账里
 */
@RestController
@RequestMapping("/bigagent/settletransfer/")
@Api(tags="大渠道商 结算转账里")
@Slf4j
public class BigAgentSettleTransferController {


    @Autowired
    private AsyncExportManager asyncExportManager;
    //异步下载每页查询500条
    private static final Integer CURRTOTAL = 500;

    /**
     * 查询、列表、导出
     * 操作列：查询、重新转账(与产品沟通是否需要保留)
     */
    @DubboReference(providedBy = DubboApps.ZHENGHE_TRANS_PROVIDER)
    private TransBigAgentApi transBigAgentApi;

    @DubboReference(providedBy = DubboApps.AGENT_SERVER_PROVIDER)
    private BigAgentTransferService bigAgentTransferService;

    /**
     * 大渠道商-转账记录列表
     * @return
     */
    @AutoLog(value = "大渠道商-转账记录列表")
    @ApiOperation(value="大渠道商-转账记录列表", notes="大渠道商-转账记录列表")
    @RequestMapping(value = "/json/{filename}", method = RequestMethod.GET)
    public Result<MyIPage<BigAgentTransferVo>> page(BigAgentTransferDto query,
                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        return bigAgentTransferService.queryTransferORecord(query, pageNo, pageSize);
    }


    /**
     * 大渠道商-转账记录导出
     * @return
     */
    @AutoLog(value = "大渠道商-转账记录导出")
    @ApiOperation(value="大渠道商-转账记录导出", notes="大渠道商-转账记录导出")
    @GetMapping(value = "/export")
    public  Result<AsyncExportState> export(BigAgentTransferDto bigAgentTransferDto) {

        //获取导出数据
        log.info("大渠道商-转账记录导出>>>>>>>>bigAgentTransferDto={}",bigAgentTransferDto);

        AtomicInteger i = new AtomicInteger(1);


        return Result.success(asyncExportManager.submit(new AsyncExportHandler<BigAgentTransferVo>() {

            @Override
            public List<BigAgentTransferVo> moreData(AsyncExportContext asyncExportContext) {


                final  ResultX<MyIPage<BigAgentTransferVo>> data = bigAgentTransferService.export(bigAgentTransferDto,i.intValue(), CURRTOTAL);

                // 设置上页码和当前页，可以自动计算进度条
                asyncExportContext.setCurrPage(i);
                asyncExportContext.setPages((int) (data.getResult().getTotal() / CURRTOTAL));

                i.getAndIncrement();
                return data.getResult().getRecords();
            }
        }));

    }


    /**
     * 大渠道商-转账记录查询
     * @return
     */
    @AutoLog(value = "大渠道商-转账记录查询")
    @ApiOperation(value="大渠道商-转账记录查询", notes="大渠道商-转账记录查询")
    @GetMapping(value = "/querybysettleno")
    public Result<BigAgentSettlementResponse> queryBySettleNo(@RequestParam(value = "settleNo", required = true) String settleNo) {
        log.info("大渠道商-转账记录查询,结算单号：{}", settleNo);

        BigAgentSettlementStatusRequest request = new BigAgentSettlementStatusRequest();
        request.setSettleOrderNo(settleNo);
        ResultX<BigAgentSettlementResponse> bigAgentSettlementResponseResultX = transBigAgentApi.bigAgentSettlementStatus(request);

        if(bigAgentSettlementResponseResultX.isSuccess() && !Objects.isNull(bigAgentSettlementResponseResultX.getResult())) {
            BigAgentSettlementResponse response = bigAgentSettlementResponseResultX.getResult();
            log.info("大渠道商-转账记录查询结果：{}", response.getSettleStatus().getCode());
            // 将结果返回前端，由前端处理
            return Result.success(response);
        }

        return Result.error("暂无查询结果，请稍后重试");
    }


    /**
     * 大渠道商-转账记录重新转账
     * @return
     */
    @AutoLog(value = "大渠道商-转账记录下载回单")
    @ApiOperation(value="大渠道商-转账记录下载回单", notes="大渠道商-转账记录下载回单")
    @GetMapping(value = "/download")
    public Result<GetReceiptInfoResponse> download(@Validated BigAgentTransferDownDto dto) {
        log.info("大渠道商-转账记录下载回单");
        GetReceiptInfoRequest request = new GetReceiptInfoRequest();
        request.setTransferNo(dto.getTransferNo());
        request.setPayChannel(PayChannelCodeEnum.valueOf(dto.getChannel()));

        ResultX<GetReceiptInfoResponse> resultX = transBigAgentApi.getTransferReceiptInfo(request);

        if(resultX.isSuccess()) {
            return Result.success(resultX.getResult());
        }
        return Result.error(resultX.getMessage());
    }


}
